package com.zdkj.subway.st.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.exceltools.IExcelExport;
import com.zdkj.common.core.util.R;
import com.zdkj.common.core.util.SpringContextHolder;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.st.dto.in.SwTkTicketTestDTO;
import com.zdkj.subway.st.dto.out.SwTkTicketTestOutDTO;
import com.zdkj.subway.st.entity.SwTkTicketTest;
import com.zdkj.subway.st.entity.SwTkTicketTestItemRef;
import com.zdkj.subway.st.entity.SwTkTicketTestResult;
import com.zdkj.subway.st.service.SwTkTicketTestItemRefService;
import com.zdkj.subway.st.service.SwTkTicketTestItemService;
import com.zdkj.subway.st.service.SwTkTicketTestResultService;
import com.zdkj.subway.st.service.SwTkTicketTestService;
import com.zdkj.subway.st.util.DateUtilsSt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ProjectName: zdkj
 * @Package: com.zdkj.subway.st.controller
 * @ClassName: SwStTicketTestController
 * @Description:
 * @Author: kangjian
 * @CreateDate: 2020/1/9 10:31
 * @Version: 1.0
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/swStTicketTest")
@Api(value = "swStTicketTest", tags = "车票测试管理")
public class SwTkTicketTestController {

    private final String STATUS_SUBMIT = "1";
    private final String STATUS_AUDIT = "3";
    private final SwTkTicketTestService swTkTicketTestService;
    /**
     * 车票测试主表与项目关联表
     */
    private final SwTkTicketTestItemRefService swTkTicketTestItemRefService;

    /**
     * 测试项目
     */
    private final SwTkTicketTestItemService swTkTicketTestItemService;
    /**
     * 车票测试结果
     */
    private final SwTkTicketTestResultService swTkTicketTestResultService;


    @GetMapping("/{id}")
    public R<SwTkTicketTestOutDTO> getById(@PathVariable Integer id) {
        SwTkTicketTestOutDTO dto = new SwTkTicketTestOutDTO();
        SwTkTicketTest test = swTkTicketTestService.getById(id);
        BeanUtils.copyProperties(test, dto);
        dto.setResult(swTkTicketTestResultService.getOne(Wrappers.<SwTkTicketTestResult>query()
                .lambda().eq(SwTkTicketTestResult::getRefTestId, test.getId())));
        List<SwTkTicketTestItemRef> listRef = swTkTicketTestItemRefService.list(Wrappers.<SwTkTicketTestItemRef>query()
                .lambda().eq(SwTkTicketTestItemRef::getRefTestId, test.getId()));
        List<Integer> listItemIds = listRef.stream().map(SwTkTicketTestItemRef::getRefItemId).collect(Collectors.toList());
        dto.setListItemIds(listItemIds);
        return R.ok(dto);
    }

    @GetMapping("/page")
    public R<IPage> getDictPage(Page page, SwTkTicketTest swTkTicketTest) {
        //测试时间
        List<String> dateCondition = swTkTicketTest.getDates1();
        LambdaQueryWrapper<SwTkTicketTest> lambdaQueryWrapper = Wrappers.query(swTkTicketTest).orderByDesc("test_submit_time","test_time").lambda();
        //String dateCondition = swTkTicketTest.getTestSubmitTimeDTO();
        if (ObjectUtil.isNotEmpty(dateCondition)) {
            lambdaQueryWrapper.between(SwTkTicketTest::getTestSubmitTime, dateCondition.get(0), dateCondition.get(1));
            //lambdaQueryWrapper.likeRight(SwTkTicketTest::getTestSubmitTime, dateCondition);
        }
        return R.ok(swTkTicketTestService.page(page, lambdaQueryWrapper));
    }

    @SysLog("车票测试保存信息")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('st_ticket_test_add')")
    public R save(@Valid @RequestBody SwTkTicketTestDTO swTkTicketTestDTO) {
        SwTkTicketTest swTkTicketTest = ObjectUtils.getDefaultObj(SwTkTicketTest.class);
        BeanUtils.copyProperties(swTkTicketTestDTO, swTkTicketTest);
        swTkTicketTestService.save(swTkTicketTest);
        SwTkTicketTestResult swTkTicketTestResult = new SwTkTicketTestResult();
        swTkTicketTestResult.setRefTestId(swTkTicketTest.getId());
        swTkTicketTestResult.setTestPersonCode(swTkTicketTest.getTestPersonId());
        swTkTicketTestResultService.save(swTkTicketTestResult);
        List<SwTkTicketTestItemRef> listRef = new ArrayList<>();
        swTkTicketTestDTO.getListItemIds().forEach(itemId -> {
            SwTkTicketTestItemRef ref = new SwTkTicketTestItemRef();
            ref.setRefTestId(swTkTicketTest.getId());
            ref.setRefItemId(itemId);
            listRef.add(ref);
        });
        if (!listRef.isEmpty()) {
            swTkTicketTestItemRefService.saveBatch(listRef);
        }
        return R.ok();
    }

    @SysLog("删除车票测试信息")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('st_ticket_test_delete')")
    public R removeById(@PathVariable String id) {
        return R.ok(swTkTicketTestService.removeById(id));
    }

    @PutMapping
    @SysLog("修改车票测试信息")
    @PreAuthorize("@pms.hasPermission('st_ticket_test_update')")
    public R updateById(@Valid @RequestBody SwTkTicketTestDTO swTkTicketTestDTO) {
        SwTkTicketTest swTkTicketTest = new SwTkTicketTest();
        BeanUtils.copyProperties(swTkTicketTestDTO, swTkTicketTest);

        //先删除旧的关联项目
        swTkTicketTestItemRefService.remove(Wrappers.<SwTkTicketTestItemRef>query()
                .lambda().eq(SwTkTicketTestItemRef::getRefTestId, swTkTicketTestDTO.getId()));

        List<SwTkTicketTestItemRef> listRef = new ArrayList<>();
        swTkTicketTestDTO.getListItemIds().forEach(itemId -> {
            SwTkTicketTestItemRef ref = new SwTkTicketTestItemRef();
            ref.setRefTestId(swTkTicketTestDTO.getId());
            ref.setRefItemId(itemId);
            listRef.add(ref);
        });
        if (!listRef.isEmpty()) {
            swTkTicketTestItemRefService.saveBatch(listRef);
        }
        return R.ok(swTkTicketTestService.updateById(swTkTicketTest));
    }

    @GetMapping("/export")
    @SysLog("导出车票测试信息")
    public void exportExcel(SwTkTicketTest swTkTicketTest, HttpServletResponse response) {
        List<SwTkTicketTest> swTkTicketTestReceivelist = swTkTicketTestService.list(Wrappers.query(swTkTicketTest));
        IExcelExport excelExport = SpringContextHolder.getBean("commonExcelExport");
        Workbook workbook = excelExport.parse(swTkTicketTestReceivelist);
        try {
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            log.error("", e);
        }
    }

    /**
     * 通过主表测试ID查找测试结果
     *
     * @param testId testId
     * @return R
     */
    @ApiOperation(value = "通过主表测试ID查找测试结果", notes = "通过主表测试ID查找测试结果")
    @GetMapping("/result/ref/{testId}")
    public R getByRefId(@PathVariable("testId") Integer testId) {
        return R.ok(swTkTicketTestResultService.getOne(Wrappers.<SwTkTicketTestResult>query().lambda()
                .eq(SwTkTicketTestResult::getRefTestId, testId)));
    }

    @ApiOperation(value = "通过主表测试ID修改测试结果", notes = "通过主表测试ID修改测试结果")
    @SysLog("通过主表测试ID修改测试结果")
    @PutMapping("/result/ref")
    public R updateById(@RequestBody SwTkTicketTestResult swTkTicketTestResult) {

        Integer refTestId = swTkTicketTestResult.getRefTestId();
        swTkTicketTestResultService.saveOrUpdate(swTkTicketTestResult);
        SwTkTicketTest swTkTicketTest = swTkTicketTestService.getById(refTestId);
        swTkTicketTest.setTestResult(swTkTicketTestResult.getTestResult());
        swTkTicketTest.setTestSubmiterId(swTkTicketTestResult.getTestPersonCode());
        swTkTicketTest.setTestTime(DateUtilsSt.newLocalDateTime());//当前时间
        return R.ok(swTkTicketTestService.updateById(swTkTicketTest));
    }

    @ApiOperation(value = "申请测试", notes = "申请测试")
    @PutMapping("/submit")
    public R submitTest(@RequestBody List<Integer> ids) {
        for (Integer id : ids) {
            SwTkTicketTest swTkTicketTest = swTkTicketTestService.getById(id);
            swTkTicketTest.setCheckStatus(STATUS_SUBMIT);
            swTkTicketTestService.updateById(swTkTicketTest);
        }
        return R.ok();
    }

    @ApiOperation(value = "批量审批", notes = "批量审批")
    @PutMapping("/audit")
    public R auditTest(@RequestBody List<SwTkTicketTest> ids) {
        for (SwTkTicketTest swTkTicketTest : ids) {
            swTkTicketTestService.updateById(swTkTicketTest);
        }
        return R.ok();
    }
}
